<template>
  <div class="app-container">
    <div class="head-container">
      <!--query form-->
      <div class="filter-container">
        <el-input v-model="queryFileds.username" placeholder="User name" size="small" style="width: 200px;" class="filter-item" />
        <el-input v-model="queryFileds.email" placeholder="Email" size="small" style="width: 200px;" class="filter-item" />

        <el-button type="success" icon="el-icon-search" class="filter-item" size="mini" @click="handleQuery">search</el-button>
        <el-button type="warning" icon="el-icon-refresh-left" class="filter-item" size="mini" @click="resetQuery">reset</el-button>
      </div>

      <!--toolbar-->
      <div>
        <el-button
          type="primary"
          icon="el-icon-plus"
          class="filter-item"
          size="mini"
          @click="handleCreate"
        >
          Add
        </el-button>

        <el-button
          type="danger"
          icon="el-icon-delete"
          class="filter-item"
          size="mini"
          :disabled="selections.length === 0"
          @click="handleBatchDelete(selections)"
        >
          Delete
        </el-button>
      </div>
    </div>

    <!--table render-->
    <div id="usersTable" style="margin-top: 15px;">
      <el-table
        :data="users"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column label="Id" align="left">
          <template slot-scope="{row}">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>

        <el-table-column label="User name" min-width="150px" align="left">
          <template slot-scope="{row}">
            <span>{{ row.username }}</span>
          </template>
        </el-table-column>

        <el-table-column label="Email" min-width="200px" align="left">
          <template slot-scope="{row}">
            <span>{{ row.email }}</span>
          </template>
        </el-table-column>

        <el-table-column label="Operation" width="200px" align="center">
          <template slot-scope="{row, $index}">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleUpdate(row)" />
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(row,$index)" />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- create or edit -->
    <el-dialog :title="dialogTitleMap[dialogType]" :visible.sync="dialogVisible" width="600px">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 470px; margin-left:50px;">
        <el-form-item label="Email" prop="email">
          <el-input v-model="temp.email" />
        </el-form-item>
        <el-form-item label="User name" prop="username">
          <el-input v-model="temp.username" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">
          Cancel
        </el-button>
        <el-button type="primary" @click="dialogType==='create'?createData():updateData()">
          Confirm
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { parseTime } from '@/utils/index'
import { listUser, createUser, updateUser, deleteUser } from '@/api/user'
export default {
  data() {
    return {
      users: [],
      queryFileds: {
        page: 1,
        limit: 20,
        username: undefined,
        email: undefined
      },
      temp: {
        id: undefined,
        username: undefined,
        email: undefined
      },
      dialogVisible: false,
      dialogType: '',
      dialogTitleMap: {
        update: 'Edit',
        create: 'Create'
      },
      rules: {
        username: [{ required: true, message: 'username is required', trigger: 'blur' }],
        email: [{ required: true, message: 'email is required', trigger: 'blur' }]
      },
      selections: []
    }
  },
  created() {
    this.handleQuery()
  },
  methods: {
    parseTime,
    handleQuery() {
      listUser(this.queryFileds).then(res => {
        this.users = res.data
      })
    },
    resetQuery() {
      this.queryFileds = {
        page: 1,
        limit: 20,
        username: undefined,
        email: undefined
      }
      this.handleQuery()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        username: undefined,
        email: undefined
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogType = 'create'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const postData = Object.assign({}, this.temp)
          createUser(postData).then((res) => {
            this.users.unshift(res.data)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogType = 'update'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const postData = Object.assign({}, this.temp)
          updateUser(postData).then((res) => {
            const index = this.users.findIndex(v => v.id === res.data.id)
            this.users.splice(index, 1, res.data)
            this.dialogVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm(`确定删除本条数据吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const userIds = []
        userIds.push(row.id)
        const requestParam = {
          userIds: userIds
        }
        deleteUser(requestParam).then(() => {
          this.$notify({
            title: 'Success',
            message: 'Delete Successfully',
            type: 'success',
            duration: 2000
          })
          this.users.splice(index, 1)
        })
      }).catch(() => {

      })
    },
    handleSelectionChange(val) {
      this.selections = val
    },
    handleBatchDelete(datas) {
      this.$confirm(`确认删除选中的${datas.length}条数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const userIds = datas.map(row => row.id)
        const requestParam = {
          userIds: userIds
        }
        deleteUser(requestParam).then(() => {
          this.$notify({
            title: 'Success',
            message: 'Delete Successfully',
            type: 'success',
            duration: 2000
          })
          // refresh
          this.handleQuery()
        })
      }).catch(() => {
      })
    }
  }
}
</script>
<style scoped>
.select-box span:focus-within {
  border: none;
  outline: none;
}
</style>
